/**
 * This is a read-only API for Appalachian.  You can retrieve
 * information about what Appalachian is storing, but you can't
 * append or modify any of it via the API.  Users should use
 * Appalachian themselves to change any OpenID information.
 */

var AppalachianAPI = function() {
	this.load();
};

/**
 * Loads all the relevant Appalachian scripts.
 */
AppalachianAPI.prototype.load = function() {
	document.write("<script type='application/x-javascript' src='chrome://appalachian/scripts/openid.js' />");
	document.write("<script type='application/x-javascript' src='chrome://appalachian/scripts/db.js' />");
	document.write("<script type='application/x-javascript' src='chrome://appalachian/scripts/appalachianCommands.js' />");
	document.write("<stringbundleset id='appalachian-bundleset'>");
        document.write("<stringbundle id='appalachian-query-bundle' src='chrome://appalachian/content/sql/query.sql.properties' />");
        document.write("<stringbundle id='appalachian-bundle' src='chrome://appalachian/locale/appalachian.properties' />");
        document.write("<stringbundle id='appalachian-db-bundle' src='chrome://appalachian/locale/db.properties' />");
	document.write("</stringbundleset>");
};

/**
 * List all OpenIDs that Appalachian knows about.
 */
AppalachianAPI.prototype.list = function() {
	var ids = AppalachianDB.listAll();
	return ids;
};

/**
 * Check if an OpenID is within Appalachian's stores.
 */
AppalachianAPI.prototype.exists = function(openid) {
	return AppalachianDB.exists(openid);
};

/**
 * Check if an OpenID and its use are within Appalachian's stores.
 */
AppalachianAPI.prototype.useExists = function(openid, url) {
	return AppalachianDB.useExists(openid, url);
};

/**
 * Initiate a login; takes a continuation function as login that takes
 * continuation functions as arguments - success and failure
 */
AppalachianAPI.prototype.login = function(openid, target, login) {
	// extension finds out it needs to login
	// open target in new tab
	gBrowser.selectedTab = gBrowser.addTab(target);
	var tab = gBrowser.selectedTab;
	// look up openid
	var id = AppalachianDB.getInfoByUrl(openid);
	// get use info
	var useid = AppalachianDB.getUseId(id, target);
	var use = AppalachianDB.getUse(useid, id);
	// 'fake' the click for a login
	AppalachianCommands.useID(id, use["field"], use["form"]);
	var success = function() {
		gBrowser.removeTab(tab);
		// now in verifying state... then what?
	};
	var failure = function() {
		Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT);
		gBrowser.removeTab(tab);
		// application should do its own warnings for failure
	};

	// control is surrendered to calling application when cycle
	// returns to doIdle state

	// the calling application should be able to tell if the user
	// has successfully logged in or not and call continuations
	// appropriately

	this.apiLogin = function() {login(openid, target, success, failure);};
};
